<?php

namespace app\api\controller;

use app\facade\Redis;
use app\models\{User as Users, Machine, MachineLog, Config, Team, UserAuth, UserSafety};
use think\Facade\Config as Configs;
use think\Validate;
use think\Db;

class Minging extends Base
{
    //注册账号
    public function lists()
    {
        $list = (new Machine())->where('status', 1)->field('direct_push,purchpeople,teampeople,created,algebra,status', true)->select();
        $this->result($list, 0, '获取成功');
    }

    public function give_lists()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $validate = new Validate([
                'id' => 'require',
            ], [
                'id.require' => '矿机ID不能为空',
            ]);
            if (!$validate->check($data)) {
                $this->result([], 1, $validate->getError());
            }
            $auth = (new UserAuth())->where('user_id', $this->request->user_id)->find();
            if (empty($auth) || $auth['status'] != 2) {
                $this->result([], 1, '未进行身份认证，无法领取');
            }
            $safety = (new UserSafety())->where(['user_id' => $this->request->user_id, 'type' => [1, 2, 3]])->count();
            if ($safety < 3) {
                $this->result([], 1, '必须已绑定微信、支付宝、银行卡才能领取');
            }
            $machine = (new Machine())->where(['id' => $data['id'], 'status' => 1])->find();
            if (empty($machine)) {
                $this->result([], 1, '矿机不存在或已下架');
            }
            $haveMachineLog = (new MachineLog())->where(['user_id' => $this->request->user_id, 'mining_id' => $machine['id'], 'type' => 2])->count();
            if ($haveMachineLog > 0) {
                $this->result([], 1, '您已领取该类型矿机，无法重复领取');
            }
            //获取团队累计代数
            $MachineRewards = (new Config())->where('key', 'machine_rewards')->value('value');
            $MachineRewards = empty($MachineRewards) ? 10 : (int)$MachineRewards;
            $tree = [];
            if ($MachineRewards < 1) {
                $this->result([], 1, '获取失败');
            }
            for ($i = 1; $i <= $MachineRewards; $i++) {
                $tree[] = $i;
            }
            $ones = 0; //直推人数
            $machines = 0; //团队总矿机数
            $powers = 0; //团队算力
            $team = []; //团队人员
            //获取团队所有人
            $myteam = (new Team())->field('supe_id,algebra')->where(['user_id' => $this->request->user_id, 'algebra' => $tree])->select();
            //整个团队信息
            foreach ($myteam as $teams) {
                if ($teams['algebra'] == 1) {
                    $ones += 1;
                }
                //团队用户ID
                $team[] = $teams['supe_id'];
            }
            if (count($team) > 0) {
                $machines = (new MachineLog())->where(['user_id' => $team])->count();
                $powers = (new Users())->where(['id' => $team])->sum('power');
            }
            if ($ones < $machine['direct_push'] || $machines < $machine['purchpeople'] || $powers < $machine['teampeople']) {
                $this->result([], 1, '未达到领取条件');
            }
            Db::startTrans();
            try {
                $id = (new MachineLog())->insertGetId([
                    'user_id' => $this->request->user_id,
                    'buymoney' => $machine['price'],
                    'power' => $machine['power'],
                    'mining_id' => $machine['id'],
                    'dividends' => $machine['dividends'],
                    'day_dividends' => $machine['day_dividends'],
                    'day' => $machine['day'],
                    'lave_day' => $machine['day'],
                    'type' => 2,
                    'days' => date('Y-m-d H:i:s')
                ]);
                if ($machine['power'] > 0) {
                    (new Users())->MoneyEdit($this->request->user_id, $this->request->user['power'], $machine['power'], 5, 1, '购买矿机', $id, 0, 0, 0);
                }
                Redis::lPush('lists', $this->request->user_id);
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                $this->result([], 1, '领取失败，请重试');
            }
            $this->result([], 0, '领取成功');
        } else {
            //获取团队累计代数
            $MachineRewards = (new Config())->where('key', 'machine_rewards')->value('value');
            $MachineRewards = empty($MachineRewards) ? 10 : (int)$MachineRewards;
            $tree = [];
            if ($MachineRewards < 1) {
                $this->result([], 1, '获取失败');
            }
            for ($i = 1; $i <= $MachineRewards; $i++) {
                $tree[] = $i;
            }
            $ones = 0; //直推人数
            $machines = 0; //团队总矿机数
            $powers = 0; //团队算力
            $team = []; //团队人员
            //获取团队所有人
            $myteam = (new Team())->field('supe_id,algebra')->where(['user_id' => $this->request->user_id, 'algebra' => $tree])->select();
            //整个团队信息
            foreach ($myteam as $teams) {
                if ($teams['algebra'] == 1) {
                    $ones += 1;
                }
                //团队用户ID
                $team[] = $teams['supe_id'];
            }
            if (count($team) > 0) {
                $machines = (new MachineLog())->where(['user_id' => $team])->count();
                $powers = (new Users())->where(['id' => $team])->sum('power');
            }
            $list = (new Machine())->where('status', 1)->field('created,algebra,status', true)->select();
            foreach ($list as $lists) {
                //判断是否达到领取条件
                if ($ones >= $lists['direct_push'] && $machines >= $lists['purchpeople'] && $powers >= $lists['teampeople']) {
                    $lists['receive'] = 2;
                } else {
                    $lists['receive'] = 1;
                }
                //判断是否已经领取
                $haveMachineLog = (new MachineLog())->where(['user_id' => $this->request->user_id, 'mining_id' => $lists['id'], 'type' => 2])->count();
                if ($haveMachineLog > 0) {
                    $lists['havemachine'] = 2;
                } else {
                    $lists['havemachine'] = 1;
                }
            }
            $this->result($list, 0, '获取成功');
        }
    }

    public function buy_machine()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $validate = new Validate([
                'id' => 'require',
                'trade' => 'require',
            ], [
                'id.require' => '矿机ID不能为空',
                'trade.require' => '交易密码不能为空',
            ]);
            if (!$validate->check($data)) {
                $this->result([], 1, $validate->getError());
            }
            $user = $this->request->user;
            if (md5(md5($data['trade'])) != $user['trade']) {
                $this->result([], 1, '交易密码错误');
            }
            $auth = (new UserAuth())->where('user_id', $this->request->user_id)->find();
            if (empty($auth) || $auth['status'] != 2) {
                $this->result([], 1, '未进行身份认证，无法领取');
            }
            $safety = (new UserSafety())->where(['user_id' => $this->request->user_id, 'type' => [1, 2, 3]])->count();
            if ($safety < 3) {
                $this->result([], 1, '必须已绑定微信、支付宝、银行卡才能购买');
            }
            $machine = (new Machine())->where(['id' => $data['id'], 'status' => 1])->find();
            if (empty($machine)) {
                $this->result([], 1, '矿机不存在或已下架');
            }

            $haveMachineLog = (new MachineLog())->where(['user_id' => $this->request->user_id, 'mining_id' => $machine['id'], 'type' => 1, 'status' => 1])->count();
            if (($haveMachineLog + 1) > $machine['limits']) {
                $this->result([], 1, '该类型矿机每人限购' . $machine['limits'] . '台');
            }
            if ($this->request->user['money'] < $machine['price']) {
                $this->result([], 1, '资产数目不足，无法购买');
            }
            Db::startTrans();
            try {
                $id = (new MachineLog())->insertGetId([
                    'user_id' => $this->request->user_id,
                    'buymoney' => $machine['price'],
                    'power' => $machine['power'],
                    'mining_id' => $machine['id'],
                    'dividends' => $machine['dividends'],
                    'day_dividends' => $machine['day_dividends'],
                    'day' => $machine['day'],
                    'lave_day' => $machine['day'],
                    'type' => 1,
                    'days' => date('Y-m-d H:i:s')
                ]);
                if ($machine['price'] > 0) {
                    (new Users())->MoneyEdit($this->request->user_id, $this->request->user['money'], -$machine['price'], 1, 1, '购买矿机', $id, 0, 0, 0);
                }
                if ($machine['power'] > 0) {
                    (new Users())->MoneyEdit($this->request->user_id, $this->request->user['power'], $machine['power'], 5, 2, '购买矿机', $id, 0, 0, 0);
                }
                Redis::lPush('lists', $this->request->user_id);
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                $this->result([], 1, '购买失败，请重试');
            }
            $this->result([], 0, '购买成功');
        } else {
            $status = $this->request->get('status/d', '');
            $list = (new MachineLog())->order('id desc')->order('id desc');
            if (!empty($status)) {
                $list = $list->where('status', $status);
            }
            $list = $list->where(['user_id' => $this->request->user_id])->field('user_id,text,created', true)->paginate(20, false, ['query' => $this->request->param()]);
            foreach ($list as $lists) {
                $lists['lave_dividends'] = round($lists['day_dividends'] * $lists['lave_day'], 2);
                $machine = (new Machine())->where(['id' => $lists['mining_id']])->find();
                $lists['name'] = $machine['name'];
                $lists['cover'] = $machine['cover'];
            }
            $this->result($list, 0, '获取成功');
        }
    }

    public function Receive()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $validate = new Validate([
                'id' => 'require',
            ], [
                'id.require' => '矿机ID不能为空',
            ]);
            if (!$validate->check($data)) {
                $this->result([], 1, $validate->getError());
            }
            $machine = (new MachineLog())->where(['id' => $data['id'], 'user_id' => $this->request->user_id, 'status' => 1])->find();
            if (empty($machine)) {
                $this->result([], 1, '矿机不存在或已完成');
            }
            if ($machine['income'] <= 0) {
                $this->result([], 1, '无收益领取');
            }
            if ($machine['lave_day'] <= 0) {
                $status = 2;
            } else {
                $status = 1;
            }
            $user = $this->request->user;
            Db::startTrans();
            try {
                (new Users())->MoneyEdit($user['id'], $user['amount'], $machine['day_dividends'], 2, 1, '矿机收益', $machine['id'], 0, 0, 0);
                (new MachineLog())->where(['id' => $data['id'], 'user_id' => $this->request->user_id])->update(['status' => $status, 'income' => 0]);
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                $this->result([], 1, '领取失败，请重试');
            }
            $this->result([], 0, '领取成功');
        }
    }
}
